package com.ljq.event.session;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @Author linjq
 * @Date 17/7/28 下午11:19
 */
public class HttpSessionImpl extends MockHttpSession implements HttpSession {

    private HttpServletRequest request;

    private HttpServletResponse response;

    //@Autowired
    private RedisTemplate<String, String> rds;


    public HttpSessionImpl(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        if(null==rds) {
            ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            rds = (RedisTemplate<String, String>) ac.getBean("redisTemplate");
        }
    }


    @Override
    public Object getAttribute(String s) {
        String sessionId = getSessionIdFromCookie();
        String session = rds.opsForValue().get(sessionId);
        return session;
    }

    @Override
    public void setAttribute(String s, Object o) {
        //String key = Math.random() + "--" + request.getParameter("username");
        rds.opsForValue().set(s, (String) o);
    }

    private String getSessionIdFromCookie(){
        Cookie[] cookies = request.getCookies();
        if(cookies!=null) {
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("sessionId")) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
